<?php
namespace app\index\controller;
use think\Controller;
use think\Image;
use think\Request;
class Pay extends Controller
{
    // 文件上传表单
    public function notify()
    {
    include EXTEND_PATH . 'wxpay/lib/WxPay.Api.php';
    include EXTEND_PATH . 'wxpay/lib/WxPay.Notify.php'; 
    $xml = file_get_contents("php://input");
    $data = \WxPayResults::Init($xml);
    //dump($data);exit;
    if (!array_key_exists("transaction_id", $data)) {
        return $this->toXML(['return_code' => 'FAIL', 'return_msg' => '参数错误']);
    }
    //查询订单，判断订单真实性
    if (!$data["out_trade_no"] || !$this->Queryorder($data["transaction_id"])) {
        return $this->toXML(['return_code' => 'FAIL', 'return_msg' => '订单真实性存疑']);
    }
    $outTradeNo = $data['out_trade_no'];
     $pay = model('Deal')->get(['trade_no' => $outTradeNo]);
     if (!$pay) {
         return $this->toXML(['return_code' => 'FAIL', 'return_msg' => '订单不存在']);
     }
     if($pay->pay_status == 1) {
           return $this->toXML(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
        }
   try {
        $payrRes = model('DeaL')->updatePay($outTradeNo, $data);
        } catch (\Exception $e) {
           return false;
        }
    return $this->toXML(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
}

/// 查询订单
 
  private function Queryorder($transaction_id)
  {
    $input = new \WxPayOrderQuery();
    $input->SetTransaction_id($transaction_id);
    $result = \WxPayApi::orderQuery($input);
    if(array_key_exists("return_code", $result)
        && array_key_exists("result_code", $result)
        && $result["return_code"] == "SUCCESS"
        && $result["result_code"] == "SUCCESS")
    {
        return true;
    }
    return false;
  }

 //array转xml
    public function toXML($values)
    {
    if(!is_array($values) || count($values) <= 0) {
        return "<xml></xml>";
    }//

    $xml = "<xml>";
    foreach ($values as $key => $val) {
        if (is_numeric($val)) {
            $xml.="<".$key.">".$val."</".$key.">";
        }else{
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
    }//
    $xml.="</xml>";
    return $xml; 
    }
 
}
